package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.ControlRenovateRectificationMapper;
import com.bf.electroplating.pojo.dto.renovate.ControlProblemRenovateQueryDTO;
import com.bf.electroplating.pojo.dto.renovate.ControlRenovateRectificationDTO;
import com.bf.electroplating.pojo.entity.ControlProblemRenovate;
import com.bf.electroplating.pojo.entity.ControlRenovateRectification;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.pojo.enums.RectificationStatusEnum;
import com.bf.electroplating.pojo.vo.renovate.ControlProblemRenovateVO;
import com.bf.electroplating.pojo.vo.renovate.ControlRenovateRectificationVO;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.ControlProblemRenovateService;
import com.bf.electroplating.service.ControlRenovateRectificationService;
import com.bf.electroplating.service.PubAttachmentService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 15451
 * @description 针对表【control_renovate_rectification(整改记录表)】的数据库操作Service实现
 * @createDate 2025-06-26 11:03:27
 */
@Slf4j
@Service
public class ControlRenovateRectificationServiceImpl extends ServiceImpl<ControlRenovateRectificationMapper, ControlRenovateRectification>
        implements ControlRenovateRectificationService {

    @Resource
    private PubAttachmentService attachmentService;

    @Resource
    private ComCompanyService companyService;

    @Resource
    private ControlProblemRenovateService renovateService;

    @Override
    public Page<ControlProblemRenovateVO> pageList(ControlProblemRenovateQueryDTO dto) {
        Page<ControlProblemRenovateVO> page = renovateService.page(dto);
        page.getRecords().forEach(item -> {
            List<ControlRenovateRectification> list = list(new LambdaQueryWrapper<ControlRenovateRectification>().eq(ControlRenovateRectification::getRId, item.getId())
                    .orderByDesc(ControlRenovateRectification::getRectificationTime));
            if (!CollectionUtils.isEmpty(list)) {
                item.setRectificationTime(getDateStr(list.get(0).getRectificationTime()));
                item.setRectificationDescription(list.get(0).getRectificationDescription());
                item.setRectificationPhotoList(attachmentService.getWholeFile(list.get(0).getId(), AttModuleEnums.RENOVATE_RECTIFICATION_PHOTO.getCode()));
            }
        });
        return page;
    }

    @Override
    public ControlRenovateRectificationVO detail(String id) {
        ControlProblemRenovateVO vo = renovateService.detail(id);
        ControlRenovateRectificationVO rectificationVO = new ControlRenovateRectificationVO();
        BeanUtils.copyProperties(vo, rectificationVO);
        List<ControlRenovateRectificationDTO> list = new ArrayList<>();
        List<ControlRenovateRectification> rects = list(new LambdaQueryWrapper<ControlRenovateRectification>()
                .eq(ControlRenovateRectification::getRId, id).orderByDesc(ControlRenovateRectification::getRectificationTime));
        rects.forEach(item -> {
            ControlRenovateRectificationDTO rectificationDTO = new ControlRenovateRectificationDTO();
            rectificationDTO.setRectificationDescription(item.getId());
            rectificationDTO.setRectificationTime(getDateStr(item.getRectificationTime()));
            rectificationDTO.setRectificationDescription(item.getRectificationDescription());
            rectificationDTO.setRectificationPhotoList(attachmentService.getWholeFile(item.getId(), AttModuleEnums.RENOVATE_RECTIFICATION_PHOTO.getCode()));
            list.add(rectificationDTO);
        });
        rectificationVO.setRectificationList(list);
        return rectificationVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rectification(ControlRenovateRectificationDTO dto) {
        // 获取整改问题
        ControlProblemRenovate renovate = renovateService.getById(dto.getRId());
        if (renovate == null) {
            throw new RuntimeException("整改问题不存在");
        }

        // 创建整改记录
        ControlRenovateRectification rectification = new ControlRenovateRectification();
        rectification.setRId(dto.getRId());
        rectification.setRectificationDescription(dto.getRectificationDescription());

        // 转换整改时间
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (StringUtils.isNotBlank(dto.getRectificationTime())) {
                rectification.setRectificationTime(sdf.parse(dto.getRectificationTime()));
            } else {
                rectification.setRectificationTime(new Date());
            }
        } catch (Exception e) {
            log.error("日期解析失败：" + e.getMessage());
            throw new RuntimeException("日期格式错误");
        }

        // 保存整改记录
        save(rectification);

        // 更新整改问题状态
        if (isNotSameDay(renovate.getTimeLimit(),rectification.getRectificationTime()) && renovate.getTimeLimit().before(rectification.getRectificationTime())){
            renovate.setRectificationStatus(RectificationStatusEnum.YET_OVER.getCode());
        }else {
            renovate.setRectificationStatus(RectificationStatusEnum.YET.getCode());
        }
        renovateService.updateById(renovate);

        // 保存整改照片
        if (dto.getRectificationPhotoList() != null && !dto.getRectificationPhotoList().isEmpty()) {
            attachmentService.saveWholeAttachmentRel(dto.getRectificationPhotoList(), rectification.getId(),
                    AttModuleEnums.RENOVATE_RECTIFICATION_PHOTO.getCode());
        }
    }

    private boolean isNotSameDay(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);

        return cal1.get(Calendar.YEAR) != cal2.get(Calendar.YEAR) ||
                cal1.get(Calendar.MONTH) != cal2.get(Calendar.MONTH) ||
                cal1.get(Calendar.DAY_OF_MONTH) != cal2.get(Calendar.DAY_OF_MONTH);
    }

    private String getDateStr(Date date) {
        if (date == null) {
            return null;
        }
        LocalDate localDate = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return formatter.format(localDate);
    }
}




